import { useRoutes, useNavigate, useLocation } from "react-router-dom"
import { useEffect, useMemo } from "react"
import { useSelector, useDispatch } from "react-redux"
import { constantRoutes, asyncRoutes } from "@/pages/index"
import { getInfo } from "@/store/actions"
import { generateRoutes } from "@/store/permission"

function Page() {
  const { token, roles, accessRoutes } = useSelector(state => state.user);
  const dispatch = useDispatch();
  const navigator = useNavigate();
  const { pathname } = useLocation();
//白名单
  const whiteList = ["/login"];

  useEffect(() => {
    //token从无到有，有了token才能获取信息
    if (token) {
      dispatch(getInfo())
    } else {
      navigator("/login", { replace: true })
    }

  }, [token])

  useEffect(() => {
    if (roles && roles.length > 0) {
      // roles是一个数组，里面包含了角色，配合路由总表+算法，生成当前用户可以访问的路由规则们
      dispatch(generateRoutes(asyncRoutes, roles))
    }
  }, [roles])

  useEffect(() => {
    if (accessRoutes && accessRoutes.length > 0) {
      navigator("/dashboard", { replace: true })
    }
  }, [accessRoutes]);

  useEffect(() => {
    // !whiteList.includes(pathname)表示访问的路径并没有在白名单中，
    // 如在白名单中则不需要token
    if (!whiteList.includes(pathname) && !token) {
      navigator("/login", { replace: true })
    }
    //已经登录过有token，又访问登录页
    if (token && pathname === "/login") {
      navigator("/", { replace: true })
    }
    //访问了/，还需要重定向到/dashboard
    if (token && pathname === "/") {
      navigator("/dashboard", { replace: true })
    }
  }, [pathname])
  //计算全部路由规则
  const routes = useMemo(() => {
    const result = [...constantRoutes];
    result[0].children = accessRoutes
    return result;
  }, [accessRoutes]);


  const element = useRoutes(constantRoutes)
  return element;
}

export default Page;